<?php
/**
 * 得意基础库(分页通用处理函数)
 *
 * @author liang<lang@vip.deyi.com>
 * @since   2015/5/29 9:30
 * @copyright  deyi.com
 */

namespace Deyi\Functions;

use Apps\Common\Constant\BusinessConstant;
use Apps\Common\Controller\BaseController;

/**
 * Class PageFunction
 * @package Deyi\Functions
 */
class PageFunction
{

    /**
     *  获取合法的页号和查询偏移量
     *
     * @author liang<lang@vip.deyi.com>
     * @param $page
     * @param $size
     * @return array
     */
    public static function getPageAndOffset($page, $size)
    {

        if (empty($page) || $page < 0) {
            $page = 1;
        }

        if ($page > BusinessConstant::MAX_PAGE) {
            $page = BusinessConstant::MAX_PAGE;
        }

        // 如果接口有指定的pagesize，那么就根据接口指定计算分页
        if (BaseController::$PAGE_SIZE && (BaseController::$PAGE_SIZE <= 100) && (BaseController::$PAGE_SIZE >= 1)) {
            $size = BaseController::$PAGE_SIZE;
        }

        $offset = ($page - 1) * $size;

        return ['page' => $page, 'offset' => $offset, 'size' => $size];
    }

    /**
     *  获取分页HTML
     *
     * @author liang<lang@vip.deyi.com>
     * @param $curPage
     * @param $itemCount
     * @param $pageSize
     * @param $baseUrl
     * @param $queryParams
     * @param $style
     * @return string
     */
    public static function getPageHtml($curPage, $itemCount, $pageSize, $baseUrl, $queryParams, $style)
    {

        $paginator = new Paginator($curPage, $itemCount, $pageSize, $baseUrl, $queryParams);

        return $paginator->getHtml($style);
    }


    /**
     *  判断是否有下一页
     *
     * @author liang<lang@vip.deyi.com>
     * @param $total
     * @param $curPage
     * @param int $pageSize
     * @return int
     */
    public static function hasNextPage($total, $curPage, $pageSize = BusinessConstant::PAGE_SIZE)
    {
        $totalPage = ceil($total / $pageSize);

        $nextPage = ($curPage < $totalPage && $curPage < BusinessConstant::MAX_PAGE) ? $curPage + 1 : 0;

        return $nextPage;
    }

    /**
     * 配合nextpage构造prevpage
     * @version APP6.3.0
     * @author lang@vip.deyi.com
     * @param $curPage
     * @param $nextPage
     * @return int
     */
    public static function getPrevPage($curPage, $nextPage)
    {
        if ($curPage == 1) {
            return 0;
        }

        return $nextPage ? ($nextPage - 2) : ($curPage - 1);
    }
}
